﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;

namespace Services.BackgrondWorkerService
{
    /// <summary>
    /// 
    /// </summary>
    public static class BackgroundWorker
    {
        /// <summary>
        /// Runs the worker async.
        /// </summary>
        /// <param name="work">The work.</param>
        /// <param name="workAfterCompleted">The work after completed.</param>
        /// <param name="applicationMustBeBusy">if set to <c>true</c> [application must be busy].</param>
        /// <param name="applicationBusyMessage">The application busy message.</param>
        public static void RunWorkerAsync(Action work, Action workAfterCompleted, Action workIfError)
        {

            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            worker.DoWork += (o, ea) => work();

            worker.RunWorkerCompleted += (o, ea) =>
                {
                    if (ea.Error != null)
                        if (workIfError != null)
                            workIfError();

                    if (workAfterCompleted != null)
                        workAfterCompleted();

                };
            worker.RunWorkerAsync();
        }

        /// <summary>
        /// Runs the worker async.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="work">The work.</param>
        /// <param name="workAfterCompleted">The work after completed.</param>
        /// <param name="applicationMustBeBusy">if set to <c>true</c> [application must be busy].</param>
        /// <param name="applicationBusyMessage">The application busy message.</param>
        public static void RunWorkerAsync<T>(Func<T> work, Action<T> workAfterCompleted)
        {
            System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();

            T parameter = default(T);

            worker.DoWork += (o, ea) =>
                {
                    // Astuce pour faire apparaitre la barre de progres systematiquement
                    System.Threading.Thread.Sleep(1500);
                    parameter = work();
                };

            worker.RunWorkerCompleted += (o, ea) =>
            {
                if (workAfterCompleted != null)
                    workAfterCompleted(parameter);
            };

            worker.RunWorkerAsync();
        }

    }
}
